const db = require('../config/db');

// 图书查询
exports.listBook = (req, res) => {
  // category分类 page页数  size每页显示几条数据
  let { category, page, size } = req.query;
  // 数据库返回数组的起始索引
  page = (page - 1) * size;
  let pageSql = 'select * from books where del=0 and category=? order by id limit ?,?';
  let totalSql = 'select count(*) as total from books where del=0 and category=?';
  //  page截取的起始索引  size截取的数据条数   resPage表示返回的存储截取数据的数组
  db.query(pageSql, [category, Number(page), Number(size)], (err, resPage) => {
    if (err) return res.send(err.message);
    db.query(totalSql, [category], (err, resTotal) => {
      if (err) return res.send(err.message);
      res.send({
        status: 200,
        // resTotal[0].total表示某个分类总共有多少条数据
        data: {
          total: resTotal[0].total,
          list: resPage,
        },
      });
    });
  });
};

// 图书修改
exports.updateBookById = (req, res) => {
  let { title, price, id } = req.query;
  let arr = [];
  let changeSql = 'update books set ';
  // 修改标题和价格
  if (title && price) {
    changeSql = changeSql + 'title=?,price=? where id=?';
    arr = [title, Number(price), Number(id)];
  } else if (title) {
    // 修改图书标题
    changeSql = changeSql + 'title=? where id=?';
    arr = [title, Number(id)];
  } else if (price) {
    // 修改图书价格
    changeSql = changeSql + 'price=? where id=?';
    arr = [Number(price), Number(id)];
  }
  db.query(changeSql, arr, (err, results) => {
    if (err) return res.send(err.message)
    res.send({
      status: 200,
      data: {
        message: '修改成功',
      },
    });
  });
};

// 删除图书
exports.deleteBookById = (req, res) => {
  let { id } = req.query;
  let deleteSql = 'update books set del=1 where id=?';
  db.query(deleteSql, id, (err, results) => {
    if (err) return res.send(err.message)
    res.send({
      status: 200,
      data: {
        message: '删除成功',
      },
    });
  });
};

// 添加图书
exports.addBook = (req, res) => {
  let { title2, book_img2, price2, category2 } = req.query
  let addSql = 'insert into books set ?'
  db.query(addSql, { title: title2, book_img: book_img2, point: 9.50, price: price2, category: category2, del: 0 }, (err, results) => {
    if (err) return res.send(err.message)
    res.send({
      status: 200,
      data: {
        message: '添加成功',
      },
    });
  });
}

// 获取全部图书
exports.bookData = (req, res) => {
  let sql = 'select * from books'
  db.query(sql, (err, results) => {
    if (err) return res.send(err.message)
    res.send({
      status: 200,
      data: results
    })
  })
}